package com.cino.org.controller;
import com.cino.basic.annotation.PreAuthorize;
import com.cino.basic.util.AjaxResult;
import com.cino.basic.util.PageList;
import com.cino.org.domain.Department;
import com.cino.org.query.DepartmentQuery;
import com.cino.org.service.DepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@Api(value = "部门的API",description="部门相关的CRUD功能")
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @ApiOperation(value = "通过ID查询" )
    @GetMapping("/{id}")
    @PreAuthorize(name= "查询单个部门" ,sn= "department:getOne")
    public Department loadById(@PathVariable("id") Long id){
        return departmentService.loadById(id);
    }

    @ApiOperation(value = "查询所有" )
    @GetMapping
    @PreAuthorize(name= "查询所有部门" ,sn= "department:getAll")
    public List<Department> loadAll(){
        return departmentService.loadAll();
    }

    @ApiOperation(value = "通过ID删除" )
    @DeleteMapping("/{id}")
    @PreAuthorize(name= "部门删除" ,sn= "department:delete")
    public AjaxResult del(@PathVariable("id")Long id){
        try {
            departmentService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    @ApiOperation(value = "添加或修改" )
    @PutMapping
    @PreAuthorize(name= "添加或修改" ,sn= "department:save")
    public AjaxResult addorUpdate(@RequestBody Department department){
        try {
            if(department.getId()==null){
                departmentService.save(department);
            }else{
                departmentService.update(department);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    @ApiOperation(value = "分页查询" )//高级查询和分页查询都用的post
    @PostMapping
    @PreAuthorize(name= "分页列表权限" ,sn= "department:list")
    public PageList<Department> pageQuery(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.pageQuery(departmentQuery);
    }

    @ApiOperation(value ="接口：批量删除")
    @PatchMapping
    @PreAuthorize(name= "部门批量删除" ,sn= "department:patchDel")
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            //1.调用service的方法
            departmentService.patchDelete(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    @ApiOperation(value = "接口：部门无限极树")
    @GetMapping("/deptTree")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }

}